using MCTS;
using MyTimer;
using UnityEngine;

namespace Gobang
{
    public class ComputerPlayer : ChessPlayer
    {
        public float decisionTime;

        private PredictionManager manager;
        private TimerOnly timer;

        private void AfterDecision(float _)
        {
            if(manager.predictions == null || manager.predictions.Count == 0)
            {
                timer.Restart();
                return;
            }

            Vector2Int position = manager.predictions[0].Position;
            chessboard.Put(position);
        }

        protected override void Awake()
        {
            base.Awake();
            manager = PredictionManager.FindInstance();
            timer = new TimerOnly();
        }

        private void Start()
        {
            timer.Initialize(decisionTime, false);
            timer.AfterCompelete += AfterDecision;
        }

        protected override void Update()
        {
            base.Update();
            if (timer.Paused && CanPlay())
            {
                timer.Restart();
            }
        }

        private void QuickPut()
        {
            Vector2Int v = default;
            float max = 0;
            ChessboardState state = new ChessboardState(chessboard);
            foreach (Vector2Int action in state.blank)
            {
                float value = MCTSUtility.CalculateValue(state, action);
                if(value > max)
                {
                    max = value;
                    v = action;
                }
            }
            chessboard.Put(v);
        }
    }
}